<script setup lang="ts">
import {
  getConsultOrderPre,
  createConsultOrder,
  getConsultOrderPayUrl
} from '@/services/consult'
import { getPatientDetail } from '@/services/user'
import { useConsultStore } from '@/stores'
import type { ConsultOrderPreData, PartialConsult } from '@/types/consult'
import type { Patient } from '@/types/user'
import {
  showConfirmDialog,
  showDialog,
  showLoadingToast,
  showToast
} from 'vant'
import { onMounted, ref } from 'vue'
import { onBeforeRouteLeave, useRouter } from 'vue-router'
// keyof可以获取类型的key值,返回一个字面量的联合类型 每一项都是对象的key值
type Key = keyof PartialConsult
const payInfo = ref<ConsultOrderPreData>()
const patient = ref<Patient>()
const store = useConsultStore()
const router = useRouter()
const loadData = async () => {
  const res = await getConsultOrderPre({
    type: store.consult.type,
    illnessType: store.consult.illnessType
  })
  payInfo.value = res.data
  // 设置优惠券id
  store.setCoupon(payInfo.value.couponId)
}

const loadPatient = async () => {
  if (!store.consult.patientId) return
  const res = await getPatientDetail(store.consult.patientId)
  patient.value = res.data
}

onMounted(() => {
  // 刷新页面,数据不全的话,给提示
  // low的方式
  // if (
  //   store.consult.consultFlag === undefined ||
  //   store.consult.depId === undefined ||
  //   store.consult.illnessDesc === undefined ||
  //   store.consult.illnessTime === undefined ||
  //   store.consult.illnessType === undefined ||
  //   store.consult.patientId === undefined ||
  //   store.consult.type === undefined
  // ) {
  //   return showDialog({
  //     title: '温馨提示',
  //     message:
  //       '问诊信息不完整请重新填写, 如有未支付订单,可在问诊记录页面继续支付!',
  //     closeOnPopstate: false
  //   }).then(() => {
  //     router.push('/')
  //   })
  // }

  // 换种方式实现
  const validKsys: Key[] = [
    'type',
    'illnessType',
    'depId',
    'illnessDesc',
    'illnessTime',
    'consultFlag',
    'patientId'
  ]
  // every 每一个都符合条件才返回true  有一个不符合条件的就返回false
  const valid = validKsys.every((key) => store.consult[key] !== undefined)
  if (!valid) {
    return showDialog({
      title: '温馨提示',
      message:
        '问诊信息不完整请重新填写, 如有未支付订单,可在问诊记录页面继续支付!',
      closeOnPopstate: false
    }).then(() => {
      router.push('/')
    })
  }
  loadData()
  loadPatient()
})
const agree = ref(false)

//支付抽屉显示变量
const show = ref(false)
const paymentMethod = ref<1 | 0>()
const loading = ref(false)
const orderId = ref('')
// 立即支付事件
const submit = async () => {
  if (!agree.value) return showToast('请勾选我已同意支付协议')
  // 创建订单
  loading.value = true
  const res = await createConsultOrder(store.consult)
  orderId.value = res.data.id
  loading.value = false
  // 清空之前收集的数据
  store.clear()
  // 打开抽屉
  show.value = true
}
// 1. 生成订单后不可回退
onBeforeRouteLeave(() => {
  // 有orderId代表已经提交订单了 这时候不让回退
  if (orderId.value) return false
})

// 2. 生成订单后不可关闭支付抽屉
const onClose = () => {
  console.log('准备关闭了')
  return showConfirmDialog({
    title: '关闭支付',
    message: '取消支付将无法获得医生回复,医生接诊名额有限,看你惜命不?',
    cancelButtonText: '我不要命,花钱是不可能的,关闭',
    confirmButtonText: '得花钱,我要命,多少钱都行'
  })
    .then(() => {
      return false
    })
    .catch(() => {
      orderId.value = ''
      router.push('/user/consult')
      return true
    })
}

// 跳转到支付宝页面
// const pay = async () => {
//   if (paymentMethod.value === undefined) return showToast('请选择支付方式')
//   showLoadingToast({ message: '跳转支付', duration: 0 })
//   const res = await getConsultOrderPayUrl({
//     orderId: orderId.value,
//     paymentMethod: paymentMethod.value,
//     payCallback: 'http://localhost:5173/room'
//   })
//   // 跳转到支付宝页面
//   window.location.href = res.data.payUrl
// }
</script>

<template>
  <div class="consult-pay-page" v-if="payInfo">
    <cp-nav-bar title="支付" />
    <div class="pay-info">
      <p class="tit">图文问诊 {{ payInfo.payment }} 元</p>
      <img class="img" src="@/assets/avatar-doctor.svg" />
      <p class="desc">
        <span>极速问诊</span>
        <span>自动分配医生</span>
      </p>
    </div>
    <van-cell-group>
      <van-cell title="优惠券" :value="`-¥${payInfo.couponDeduction}`" />
      <van-cell title="积分抵扣" :value="`-¥${payInfo.pointDeduction}`" />
      <van-cell
        title="实付款"
        :value="`¥${payInfo.actualPayment}`"
        class="pay-price"
      />
    </van-cell-group>
    <div class="pay-space"></div>
    <van-cell-group>
      <van-cell
        title="患者信息"
        :value="`${patient?.name} | ${patient?.genderValue} | ${patient?.age}岁`"
      ></van-cell>
      <van-cell title="病情描述" :label="store.consult.illnessDesc"></van-cell>
    </van-cell-group>
    <div class="pay-schema">
      <van-checkbox v-model="agree"
        >我已同意 <span class="text">支付协议</span></van-checkbox
      >
    </div>
    <van-submit-bar
      button-type="primary"
      :price="payInfo.actualPayment * 100"
      button-text="立即支付"
      text-align="left"
      :loading="loading"
      @submit="submit"
    />
  </div>
  <cp-pay-sheet
    v-if="payInfo"
    v-model:show="show"
    :order-id="orderId"
    :actual-payment="payInfo.actualPayment"
    :on-close="onClose"
    pay-callback="/room"
  ></cp-pay-sheet>
  <!-- <van-action-sheet
    v-model:show="show"
    title="选择支付方式"
    :close-on-popstate="false"
    :closeable="false"
    :before-close="onClose"
  >
    <div class="pay-type">
      <p class="amount">￥{{ payInfo?.actualPayment }}</p>
      <van-cell-group>
        <van-cell title="微信支付" @click="paymentMethod = 0">
          <template #icon><cp-icon name="consult-wechat" /></template>
          <template #extra
            ><van-checkbox :checked="paymentMethod === 0"
          /></template>
        </van-cell>
        <van-cell title="支付宝支付" @click="paymentMethod = 1">
          <template #icon><cp-icon name="consult-alipay" /></template>
          <template #extra
            ><van-checkbox :checked="paymentMethod === 1"
          /></template>
        </van-cell>
      </van-cell-group>
      <div class="btn">
        <van-button type="primary" round block @click="pay"
          >立即支付</van-button
        >
      </div>
    </div>
  </van-action-sheet> -->
</template>

<style lang="scss" scoped>
.consult-pay-page {
  padding: 46px 0 50px 0;
}
.pay-info {
  display: flex;
  padding: 15px;
  flex-wrap: wrap;
  align-items: center;
  .tit {
    width: 100%;
    font-size: 16px;
    margin-bottom: 10px;
  }
  .img {
    margin-right: 10px;
    width: 38px;
    height: 38px;
    border-radius: 4px;
    overflow: hidden;
  }
  .desc {
    flex: 1;
    > span {
      display: block;
      color: var(--cp-tag);
      &:first-child {
        font-size: 16px;
        color: var(--cp-text2);
      }
    }
  }
}
.pay-price {
  ::v-deep() {
    .vam-cell__title {
      font-size: 16px;
    }
    .van-cell__value {
      font-size: 16px;
      color: var(--cp-price);
    }
  }
}
.pay-space {
  height: 12px;
  background-color: var(--cp-bg);
}
.pay-schema {
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: center;
  .text {
    color: var(--cp-primary);
  }
}
::v-deep() {
  .van-submit-bar__button {
    font-weight: normal;
    width: 160px;
  }
}
.pay-type {
  .amount {
    padding: 20px;
    text-align: center;
    font-size: 16px;
    font-weight: bold;
  }
  .btn {
    padding: 15px;
  }
  .van-cell {
    align-items: center;
    .cp-icon {
      margin-right: 10px;
      font-size: 18px;
    }
    .van-checkbox :deep(.van-checkbox__icon) {
      font-size: 16px;
    }
  }
}
</style>
